package com.wenge.datagroup.storage.dataprocess;

import com.wenge.datagroup.storage.util.ConfigUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @Author：WeiPengCheng
 * @Date：2022-07-27 10:55
 * @desc:多语言情感分析
 **/
public class MultilingualEmotion {
    private static Logger logger = LoggerFactory.getLogger(MultilingualEmotion.class);
    private static String url;

    public static void main(String[] args) {
        ConfigUtil.init();
        PropertyConfigurator.configure("config/log4j.properties");

        String content =
                "{\"text\":\"导读文章来源:伊秀黄瓜适量，挂面一把，香菜适量，熟花生适量，辣椒粉一勺，蒜末一勺，葱花一勺，白芝麻一勺，白糖一勺，生抽三勺，陈醋两勺..\"}";

    }

    public static void setUrl(String url) {
        MultilingualEmotion.url = url;
    }

    public static String analysis(String par) {
        long start = System.currentTimeMillis();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("text", par);

        OkHttpClient httpClient = new OkHttpClient().newBuilder().build();

        MultipartBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("id", "1")
                .addFormDataPart("content", jsonObject.toJSONString())
                .addFormDataPart("callback", "http://1.com")
                .build();

        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();

        // 4 发起请求获取响应值
        try {
            Response response = httpClient.newCall(request).execute();
            if (response.code() == 200) {
                logger.info("多语种情感分析请求成功!!");
                String data = response.body().string();
                if (JSON.parseObject(data).getString("code").equals("200")) {
                    String string = JSON
                            .parseObject(data)
                            .getJSONObject("data")
                            .getString("probability");
                    logger.info("多语种情感分析结果:" + string);
                    return string;
                }
            } else {
                logger.info("多语种情感分析接口请求异常! code:{}", response.code());
            }
        } catch (IOException e) {
            logger.error("多语种情感分析接口请求异常!");
            e.printStackTrace();
        } finally {
            logger.info("多语言情感分析接口处理耗时： " + (System.currentTimeMillis() - start) + " ms");
        }

        return null;
    }

}
